import { useEffect, useRef, useState } from 'react'
import { checkGrammar } from '@/services/grammarService'
import type { GrammarCheckResult, GrammarIssue } from '@/types/grammar'

type HistoryItem = {
  id: string
  time: string
  text: string
  corrected: string
  issues: GrammarIssue[]
}

const LS_KEY = 'grammar-history'

function loadHistory(): HistoryItem[] {
  try {
    const raw = localStorage.getItem(LS_KEY)
    return raw ? JSON.parse(raw) : []
  } catch {
    return []
  }
}

function saveHistory(list: HistoryItem[]) {
  try {
    localStorage.setItem(LS_KEY, JSON.stringify(list))
  } catch {}
}

const GrammarPage = () => {
  const [text, setText] = useState('')
  const [loading, setLoading] = useState(false)
  const [progress, setProgress] = useState(0)
  const [result, setResult] = useState<GrammarCheckResult | null>(null)
  const [error, setError] = useState<string | null>(null)
  const [history, setHistory] = useState<HistoryItem[]>(loadHistory())

  const timerRef = useRef<number | null>(null)

  // 进度条控制：开始推进到90%，完成后到100%并收起
  const startProgress = () => {
    setProgress(0)
    if (timerRef.current) window.clearInterval(timerRef.current)
    timerRef.current = window.setInterval(() => {
      setProgress((p) => {
        const next = p + Math.random() * 10
        return next >= 90 ? 90 : next
      })
    }, 200)
  }

  const finishProgress = () => {
    if (timerRef.current) {
      window.clearInterval(timerRef.current)
      timerRef.current = null
    }
    setProgress(100)
    window.setTimeout(() => setProgress(0), 500)
  }

  useEffect(() => {
    return () => {
      if (timerRef.current) window.clearInterval(timerRef.current)
    }
  }, [])

  const addHistory = (item: HistoryItem) => {
    const list = [item, ...history].slice(0, 100)
    setHistory(list)
    saveHistory(list)
  }

  const onCheck = async () => {
    setError(null)
    setResult(null)
    const content = text.trim()
    if (!content) {
      setError('请输入英文文本')
      return
    }
    setLoading(true)
    startProgress()
    try {
      const res = await checkGrammar(content)
      setResult(res)
      addHistory({
        id: `${Date.now()}_${Math.random().toString(36).slice(2, 8)}`,
        time: new Date().toISOString(),
        text: content,
        corrected: res.corrected || '',
        issues: Array.isArray(res.issues) ? res.issues : [],
      })
    } catch (e: any) {
      setError(e?.response?.data?.message || e?.message || '检测失败，请稍后重试')
    } finally {
      setLoading(false)
      finishProgress()
    }
  }

  const onRestore = (item: HistoryItem) => {
    setText(item.text)
    setResult({ corrected: item.corrected, issues: item.issues })
  }

  const onDelete = (id: string) => {
    const list = history.filter((h) => h.id !== id)
    setHistory(list)
    saveHistory(list)
  }

  const onClearAll = () => {
    setHistory([])
    saveHistory([])
  }

  const formatTime = (iso: string) => {
    try {
      const d = new Date(iso)
      return d.toLocaleString()
    } catch {
      return iso
    }
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <h1 className="text-2xl font-semibold text-gray-900">语法检查</h1>
      </div>

      {/* 进度条 */}
      {progress > 0 && (
        <div className="w-full h-2 bg-gray-200 rounded">
          <div
            className="h-2 rounded bg-gradient-to-r from-primary-500 to-secondary-500 transition-all duration-200"
            style={{ width: `${Math.min(progress, 100)}%` }}
          />
        </div>
      )}

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* 输入区 */}
        <div className="card p-4">
          <div className="flex items-center justify-between mb-2">
            <label className="block text-sm font-medium text-gray-700">英文原文</label>
            <div className="flex items-center gap-2">
              <button
                className="btn btn-xs btn-outline"
                onClick={() => setText('')}
                disabled={loading}
              >
                清空
              </button>
              <button
                className={`btn btn-primary ${loading ? 'opacity-70 cursor-not-allowed' : ''} hidden lg:inline-flex items-center gap-2`}
                onClick={onCheck}
                disabled={loading}
                aria-label="执行语法检测"
                title="执行语法检测"
              >
                <span className="inline-block h-2 w-2 rounded-full bg-white animate-pulse"></span>
                {loading ? '检测中...' : '检测 / 修正'}
              </button>
            </div>
          </div>
          <textarea
            className="w-full h-64 textarea"
            placeholder="在此粘贴或输入英文文本..."
            value={text}
            onChange={(e) => setText(e.target.value)}
          />
          {error && <div className="mt-3 text-red-500 text-sm">{error}</div>}
        </div>

        {/* 修正结果 */}
        <div className="card p-4">
          <label className="block text-sm font-medium text-gray-700 mb-2">修正结果</label>
          <textarea
            className="w-full h-64 textarea"
            value={result?.corrected || ''}
            readOnly
            placeholder="修正结果将显示在这里"
          />
        </div>
      </div>

      {/* 问题与建议 */}
      <div className="card p-4">
        <div className="flex items-center justify-between mb-3">
          <h2 className="text-lg font-semibold text-gray-900">问题与建议</h2>
          <span className="text-sm text-gray-500">
            {result?.issues?.length ? `共 ${result.issues.length} 项` : '—'}
          </span>
        </div>
        <div className="space-y-3">
          {result?.issues?.length ? (
            result.issues.map((it: GrammarIssue, idx: number) => (
              <div key={idx} className="p-3 rounded-lg border border-gray-100 bg-gray-50">
                <div className="text-xs text-gray-500 mb-1">[{it.type}]</div>
                <div className="text-sm text-gray-700">
                  <span className="text-gray-500">原文：</span>
                  <span className="font-medium break-words">{it.original}</span>
                </div>
                <div className="text-sm text-gray-700">
                  <span className="text-gray-500">建议：</span>
                  <span className="text-green-700 font-medium break-words">{it.suggestion}</span>
                </div>
                {it.explanation && (
                  <div className="text-xs text-gray-500 mt-1 break-words">{it.explanation}</div>
                )}
              </div>
            ))
          ) : (
            <div className="text-gray-500 text-sm">暂无数据</div>
          )}
        </div>
      </div>

      {/* 历史记录 */}
      <div className="card p-4">
        <div className="flex items-center justify-between mb-3">
          <h2 className="text-lg font-semibold text-gray-900">历史检测记录</h2>
          <div className="flex items-center gap-2">
            <button
              className="btn btn-sm"
              onClick={onClearAll}
              disabled={!history.length}
            >
              清空
            </button>
          </div>
        </div>

        {history.length === 0 ? (
          <div className="text-gray-500 text-sm">暂无历史记录</div>
        ) : (
          <div className="space-y-3">
            {history.map((h) => (
              <div key={h.id} className="p-3 rounded-lg border border-gray-100">
                <div className="flex items-center justify-between">
                  <div className="text-sm text-gray-600">
                    <span className="font-medium">{formatTime(h.time)}</span>
                    <span className="mx-2 text-gray-400">|</span>
                    <span>原文长度 {h.text.length}</span>
                    <span className="mx-2 text-gray-400">|</span>
                    <span>问题 {h.issues?.length || 0} 项</span>
                  </div>
                  <div className="flex items-center gap-2">
                    <button className="btn btn-xs" onClick={() => onRestore(h)}>还原到输入</button>
                    <button className="btn btn-xs btn-outline" onClick={() => onDelete(h.id)}>删除</button>
                  </div>
                </div>
                <div className="mt-2 text-xs text-gray-500 line-clamp-2">
                  原文预览：{h.text.slice(0, 160)}
                  {h.text.length > 160 ? '…' : ''}
                </div>
                <div className="mt-1 text-xs text-gray-500 line-clamp-2">
                  修正预览：{(h.corrected || '').slice(0, 160)}
                  {(h.corrected || '').length > 160 ? '…' : ''}
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  )
}

export default GrammarPage